//
//  ViewController.swift
//  Chess5
//
//  Created by apple on 2017/3/20.
//  Copyright © 2017年 apple. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {

    var chessBoard: ChessBoard
    let N = 15
    var winWindow: UILabel
    var reset: UILabel
    var logWall: UILabel
    var scoreBoard: UIView
    var backView: UILabel
    var giveUpView: UILabel
    var csView: UILabel
    var hsView: UILabel
    
    var ai: AI
    var step: Int
    var humanSteps: [Position]
    var computerSteps: [Position]
    
    var cWin:Int
    var hWin:Int
    var winViewController: UIViewController
    var controllerOnWinController: UIViewController
    
//    let dataPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0].stringByAppendingPathComponent("win.data")
    required init?(coder aDecoder: NSCoder) {
        winViewController = UIViewController()
        controllerOnWinController = UIViewController()
        
        chessBoard = ChessBoard(coder: aDecoder)!
        winWindow = UILabel(frame: CGRect(x: 100, y: 100, width: 200, height: 60))
        reset = UILabel()
        logWall = UILabel()
        
        ai = AI()
        humanSteps = [Position]()
        computerSteps = [Position]()
        
        step = 0
        cWin = 0
        hWin = 0
        scoreBoard = UIView.init(frame: CGRect(x: 760, y: 9, width: 230, height: 120))
        
        let csInfo = UILabel.init(frame: CGRect(x: 10, y: 10, width: 100, height: 40))
        csInfo.text = "机器赢："
        csInfo.textAlignment = .center
        
        csView = UILabel.init(frame: CGRect(x: 120, y: 10, width: 100, height: 40))
        csView.text = String.init(format: "%d", cWin)
        csView.textAlignment = .center
        
        let hsInfo = UILabel.init(frame: CGRect(x: 10, y: 60, width: 100, height: 40))
        hsInfo.text = "我 赢："
        hsInfo.textAlignment = .center
        
        hsView = UILabel.init(frame: CGRect(x: 120, y: 60, width: 100, height: 40))
        hsView.text = String.init(format: "%d", hWin)
        hsView.textAlignment = .center
        
        scoreBoard.addSubview(csInfo)
        scoreBoard.addSubview(csView)
        scoreBoard.addSubview(hsInfo)
        scoreBoard.addSubview(hsView)
        
        backView = UILabel.init(frame: CGRect(x: 800, y: 500, width: 200, height: 200))
        giveUpView = UILabel.init(frame: CGRect(x: 800, y: 700, width: 200, height: 200))
        
        super.init(coder: aDecoder)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.load()
        DispatchQueue.global(qos: .background).async {
            print("load the win data is running on the background queue")
            self.load()
            
            DispatchQueue.main.async {
//                print("This is run on the main queue, after the previous code in outer block")
                self.csView.text = String.init(format: "%d", self.cWin)
                self.hsView.text = String.init(format: "%d", self.hWin)
            }
        }
        // Do any additional setup after loading the view, typically from a nib.
        let rect = CGRect(x: 10,y: 10,width: 750,height: 750)
        chessBoard.frame = rect
        chessBoard.backgroundColor = UIColor.init(white: 0.9, alpha: 1.0)
        
        // 添加得分板信息
        
        self.view.addSubview(scoreBoard)
        
        self.view.addSubview(backView)
        self.view.addSubview(giveUpView)
        
        reset.text = "点击重玩"
        reset.textAlignment = .center
        reset.textColor = UIColor.white
        reset.font = UIFont.systemFont(ofSize: 16)
        reset.backgroundColor = UIColor.blue
        reset.layer.cornerRadius = 2
        let resetX = chessBoard.frame.origin.x + chessBoard.frame.size.width + 20
        let resetY = self.view.frame.size.height / 2
        reset.frame = CGRect(x: resetX,y: resetY,width: 120,height: 30)
        
        winWindow.text = "恭喜你，先手赢了,点击重玩"
        winWindow.textAlignment = .center
        winWindow.font = UIFont.systemFont(ofSize: 16)
        winWindow.textColor = UIColor.red
        winWindow.backgroundColor = UIColor.white
        winWindow.layer.opacity = 0.8

        logWall.textAlignment = .left
        logWall.textColor = UIColor.blue
        logWall.font = UIFont.systemFont(ofSize: 14)
        logWall.frame = CGRect(x: chessBoard.frame.origin.x + chessBoard.frame.size.width, y: 100, width: 300, height: 60)
        self.view.addSubview(logWall)
        
        self.view.addSubview(chessBoard)
        chessBoard.setNeedsDisplay()
        
        let tapGesture = UITapGestureRecognizer(target: self, action:#selector(handleTap))
        chessBoard.addGestureRecognizer(tapGesture)
        
        let resetHit = UITapGestureRecognizer(target: self, action:#selector(handleReset))
        reset.addGestureRecognizer(resetHit)

        // uilalbel isUserInteractionEnabled default value = false
        reset.isUserInteractionEnabled = true
//        winWindow.addSubview(reset)
        winWindow.isHidden = true
        self.view.addSubview(winWindow)
        self.view.addSubview(reset)
//        showWinWindow()
        }

    func showWinWindow() {
        var popoverController: UIPopoverPresentationController?
//        let winViewController = UIViewController()
        winViewController.modalPresentationStyle = .popover
        winViewController.preferredContentSize = CGSize(width: 200, height: 60)
        popoverController = winViewController.popoverPresentationController
        popoverController?.sourceRect = CGRect(x: 0, y: 0, width: 200, height: 60)
        popoverController?.sourceView = self.view
        popoverController?.permittedArrowDirections = .any
        popoverController?.delegate = self
        
        
        controllerOnWinController.modalPresentationStyle = .popover
        controllerOnWinController.preferredContentSize = scoreBoard.frame.size
        controllerOnWinController.popoverPresentationController?.permittedArrowDirections = .any
        controllerOnWinController.popoverPresentationController?.sourceRect = CGRect(x:0, y: 0, width: 200, height: 60)
        controllerOnWinController.popoverPresentationController?.sourceView = winWindow
//        controllerOnWinController.popoverPresentationController?.passthroughViews
        
        // add first popover view to self
        self .present(winViewController, animated: true, completion: {
            self.winViewController.view = self.winWindow
            
            self.controllerOnWinController.popoverPresentationController?.sourceRect = self.winWindow.frame
            
            // add second popover view contoller to the first popover
            self.winViewController.present(self.controllerOnWinController, animated: true, completion: {
                self.controllerOnWinController.view = self.scoreBoard
            })
            
        })
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func handleTap(sender: UITapGestureRecognizer) {
//        if sender.state == .ended {
//            showWinWindow()
            let touchPosition = sender.location(in: chessBoard)
            let x = Int(touchPosition.x / 50)
            let y = Int(touchPosition.y / 50)
            let p = Position(x: x, y: y)
            
            if ai.board[x][y] == Role.empty {
                step += 1
                humanSteps.append(p)
                chessBoard.go(player: Role.human,x: p.x, y: p.y,step: step)
                ai.go(board: &ai.board, player: Role.human, p: p)
                if ai.win(board: ai.board) == Role.human {
                    winWindow.isHidden = false
                    winWindow.text = "我赢了"
                    chessBoard.isUserInteractionEnabled = false
                    hWin += 1
                    DispatchQueue.global(qos: .background).async {
                        print("save win data is running on the background queue")
                        self.save()
                        
                        DispatchQueue.main.async {
                            //                print("This is run on the main queue, after the previous code in outer block")
//                            self.csView.text = String.init(format: "%d", self.cWin)
                            self.hsView.text = String.init(format: "%d", self.hWin)
                        }
                    }
                }
                else {
                    self.performSelector(onMainThread: #selector(itsComputerTurn), with: nil, waitUntilDone: false)
                }
            }
//        }
    }

    func handleReset(sender: UITapGestureRecognizer) {
        winWindow.isHidden = true
        step = 0
        chessBoard.lastStep = Position(x: -1, y: -1)
        ai.reset()
        humanSteps.removeAll()
        computerSteps.removeAll()
        
        chessBoard.isUserInteractionEnabled = true
        for view in chessBoard.subviews {
            view.removeFromSuperview()
        }
        chessBoard.layoutIfNeeded()
        chessBoard.isUserInteractionEnabled = true
    }

    func itsComputerTurn() {
        let startTime = Date()
        let p = ai.findPlace(board: &ai.board)
        if ai.board[p.x][p.y] == Role.empty {
            computerSteps.append(p)
            chessBoard.go(player: Role.computer,x: p.x,y: p.y,step: step)
            ai.go(board: &ai.board, player: Role.computer, p: p)
            if ai.win(board: ai.board) == Role.computer {
                winWindow.isHidden = false
                chessBoard.isUserInteractionEnabled = false
                winWindow.text = "机器人赢"
                cWin += 1
                DispatchQueue.global(qos: .background).async {
                    print("save  win data is running on the background queue")
                    self.save()
                    DispatchQueue.main.async {
                        //                print("This is run on the main queue, after the previous code in outer block")
                        self.csView.text = String.init(format: "%d", self.cWin)
//                        self.hsView.text = String.init(format: "%d", self.hWin)
                    }
                }
            }
            let endTime = Date()
            let str = String.init(format: "算: %d，time:%.1lf s,hit： %d", ai.searchCnt, endTime.timeIntervalSince1970 - startTime.timeIntervalSince1970, ai.hitCache)
            logWall.text = str
        }
        else {
            NSLog("(%d ,%d) 机器人SB了，走错了", p.x,p.y)
        }
//        winViewController.presentingViewController?.perform(#selector(dismiss), with: [true, nil], afterDelay: 5)
//        self.perform(#selector(dismiss), with: [true, nil], afterDelay: 10)
    }
    
    func load() {
        let filePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/win.dat"
        let url = URL.init(fileURLWithPath: filePath)
        
        //反归档
        do {
            let unarchiverData = try? Data.init(contentsOf: url)
            guard let unarchiverD = unarchiverData else {
                return
            }
            let unarchiver = NSKeyedUnarchiver.init(forReadingWith: unarchiverD)
            cWin = Int(unarchiver.decodeInt32(forKey: "computerWin"))
            hWin = Int(unarchiver.decodeInt32(forKey: "humanWin"))
//            NSLog("%d", cWin)
//            NSLog("%d", hWin)
            
        
        }
        
    }
    func save() {
        let filePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/win.dat"
        let url = URL.init(fileURLWithPath: filePath)
        //归档
        let data = NSMutableData()
        let archiver = NSKeyedArchiver.init(forWritingWith: data)
//        let computerWin = cWin
        archiver.encode(cWin, forKey: "computerWin")
        archiver.encode(hWin, forKey: "humanWin")
        archiver.finishEncoding()
        do {
           _ = try? data.write(to: url)
        }
    }
    
// pram marker delegate
    func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool {
        return true
    }
    
    func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
        
        var i = 0
        i += 1
        
        NSLog("d", i)
    }
}

